package easypsync.app;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.util.Log;

public class WakeOnLan {
    
	/**
	 * port for magic bit
	 */
    public static final int PORT = 9;    
    
    
    /**
     * ("192.168.178.255", "00:26:2D:06:71:61")
     * 
     * @param ipStr
     * @param macStr
     */
    public static void sendMagic(String ipStr, String macStr) {
    	try {
            byte[] macBytes = getMacBytes(macStr);
            byte[] bytes = new byte[6 + 16 * macBytes.length];
            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) 0xff;
            }
            for (int i = 6; i < bytes.length; i += macBytes.length) {
                System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
            }
            
            sendPacket(ipStr, bytes);
            
        }
        catch (Exception e) {
        	Log.w(WakeOnLan.class.getName(), "Failed to send Wake-on-LAN packet: + e");
        }
    }

	private static void sendPacket(String ipStr, byte[] bytes)
			throws UnknownHostException, SocketException, IOException {
		InetAddress address = InetAddress.getByName(ipStr);
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);
		DatagramSocket socket = new DatagramSocket();
		socket.send(packet);
		socket.close();
	}

    private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
        byte[] bytes = new byte[6];
        String[] hex = macStr.split("(\\:|\\-)");
        if (hex.length != 6) {
            throw new IllegalArgumentException("Invalid MAC address.");
        }
        try {
            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) Integer.parseInt(hex[i], 16);
            }
        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid hex digit in MAC address.");
        }
        return bytes;
    }
    
   
}